import { JsonWebTokenError, JwtPayload, TokenExpiredError } from "jsonwebtoken";
import config from "../app/config";

const jwt = require('jsonwebtoken');

/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-11-20 17:32:09
 * 天凉好个秋
 */
// 加密
export const sign = (data: any) => {
    return jwt.sign({User: data}, config.jwt.secret, {expiresIn: config.jwt.expire})
}

interface IVerify {
    User: JwtPayload,
    error: TokenExpiredError | JsonWebTokenError | null
}

// 解密
export const verify = (token: string): IVerify => {
    try {
        const { User } = jwt.verify(token, config.jwt.secret)
        return {
            User,
            error: null
        }
    } catch (error) {
        return {
            User: null,
            error: error.message
        }
    }
}